package huoye.shops.huoye.operation.activity;

import android.net.Uri;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.codeideology.android.utils.DateTimeFormat;
import com.codeideology.android.utils.StringUtils;
import com.codeideology.android.widget.pickerview.TimePickerView;
import com.google.gson.annotations.SerializedName;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.yanzhenjie.recyclerview.swipe.SwipeItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenu;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;
import com.yanzhenjie.recyclerview.swipe.touch.OnItemMoveListener;
import com.yanzhenjie.recyclerview.swipe.touch.OnItemStateChangedListener;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import commonality.timepicker.CustomDatePicker;
import huoye.shops.R;
import huoye.shops.base.BaseActivity;
import huoye.shops.base.BaseTakePhotoActivity;
import huoye.shops.base.UserManager;
import huoye.shops.common.model.OssImageData;
import huoye.shops.huoye.operation.adapter.MineEventSetAdapter;
import huoye.shops.huoye.operation.model.AddImage;
import huoye.shops.huoye.operation.model.EventOddPrizeList;
import huoye.shops.huoye.operation.model.ShopEventPrizeList;
import huoye.shops.huoye.operation.presenter.BuildEventPresenter;
import huoye.shops.huoye.operation.view.IBuildEventView;
import huoye.shops.huoye.user.model.User;
import huoye.shops.utils.PickerViewUtils;
import huoye.shops.utils.StockUtils;

public class BuildEventActivity extends BaseTakePhotoActivity implements SwipeItemClickListener,IBuildEventView {

    private boolean isStartTime;

    private Date StartDate;
    private Date EndDate;
    String userLotteryNum = "";
    String mostWinsNum = "";
    private String etImgPath;
    private boolean isClickThemeLogo;


    @BindView(R.id.build_event_et_event_theme)
    EditText etEventTheme;


    @BindView(R.id.build_event_iv_add_pic_logo)
    ImageView ivAddPicLogo;
    @BindView(R.id.build_event_iv_del_pic_logo)
    ImageView ivDelPicLogo;

    @OnClick(R.id.build_event_iv_add_pic_logo)
    void onAddPicLogoClick() {
        isClickThemeLogo = true;
        takePhoto();
    }

    @OnClick(R.id.build_event_iv_del_pic_logo)
    void onDelPicLogoClick() {
        mBuildEventPresenter.deleteOssImg(etImgPath);
    }


    @BindView(R.id.build_event_et_rule)
    EditText etRule;

    @BindView(R.id.build_event_et_lottery_number)
    EditText etLotteryNum;

    @BindView(R.id.build_event_et_winning_number)
    EditText etWinsNum;

    @BindView(R.id.build_event_tv_start_time)
    TextView tvStartTime;
    @BindView(R.id.build_event_tv_end_time)
    TextView tvEndTime;

    @BindView(R.id.build_event_rv)
    SwipeMenuRecyclerView rv;
    private BuildEventPresenter mBuildEventPresenter;


    @OnClick(R.id.build_event_ll_start_time)
    void onStartTime(){
        isStartTime = true;
        datePicker.show(StockUtils.getCurrentTime());
    }
    @OnClick(R.id.build_event_ll_end_time)
    void onEndTime(){
        isStartTime = false;
        datePicker.show(StockUtils.getCurrentTime());
    }




    private List<String> imgUrl = new ArrayList<>();


    //用来做倍率判断
    private List<String> rate = new ArrayList<>();

    @OnClick(R.id.build_event_btn_build_event)
    void onBuildEventTime(){
        RateCheck();
        String eventTheme = etEventTheme.getText().toString().trim();
        String remarks = etRule.getText().toString().trim();
        String beginTime = tvStartTime.getText().toString().trim();
        String endTime = tvEndTime.getText().toString().trim();
        userLotteryNum = etLotteryNum.getText().toString().trim();
        mostWinsNum = etWinsNum.getText().toString().trim();

        List<ShopEventPrizeList> images = adapter.getData();
       if(adapter != null || images != null ||images.size() >1) {
            for (ShopEventPrizeList image : images) {
                if(StringUtils.isNotEmpty(image.getPrizeImgPath())){
                    imgUrl.add(image.getPrizeImgPath());
                }
            }
        }



        if(imgUrl.size() > 0 ){
            for (int i = 0 ; i < images.size();i++){
                images.get(i).setPrizeImg(imgUrl.get(i));
            }
        }

        Log.e("aa====",eventTheme);
        if(!StringUtils.isNotEmpty(eventTheme)){
            makeToast("请输入活动主题");
            return;
        }
        if(!StringUtils.isNotEmpty(userLotteryNum)){
            makeToast("请输入用户抽奖次数");
            return;
        }

        if(!StringUtils.isNotEmpty(mostWinsNum)) {
            makeToast("请输入用户可中奖次数");
            return;
        }


        if(StartDate == null){
            makeToast("请选择开始时间");
            return;
        }else if(EndDate == null){
            makeToast("请选择结束时间");
            return;
        }


        Date now = new Date();
        if(!now.before(StartDate)){
            makeToast("活动时间不能早于当前时间");
            return;
        }

        mBuildEventPresenter.EventCreate(eventTheme,etImgPath,remarks,beginTime,endTime,userLotteryNum,mostWinsNum,images);


    }




    //检测概率是否相同
    private void  RateCheck(){
        boolean rate = getRate();
        if(rate){
            String temp = "";
            for (int i = 0; i < this.rate.size() - 1; i++)
            {
                temp = this.rate.get(i);
                for (int j = i + 1; j < this.rate.size(); j++)
                {
                    if (temp.equals(this.rate.get(j)))
                    {
                        makeToast("中奖概率不能相同");
                        this.rate.clear();
                        return;
                    }
                }
            }
        }
    }



    //检测概率是否等于大于100
    private boolean  addAdapterHint(){
        boolean rate = getRate();
        if(rate){
            int temp = 0;
            for (int i = 0; i < this.rate.size(); i++)
            {
                temp = Integer.valueOf(this.rate.get(i));
                if(temp >= 100 ){
                    makeToast("中奖概率最大值100,不能再创建");
                    this.rate.clear();
                    return false;
                }
            }
        }else {
            return  false;
        }

       return true;
    }

    //获取概率的值
    private boolean  getRate(){
        rate.clear();
        List<ShopEventPrizeList> list = adapter.getData();
        for (int i = 0 ;i <list.size() ; i++){
            if(StringUtils.isNotEmpty(list.get(i).getBeginNum())){
                rate.add(list.get(i).getBeginNum());
            }else {
                makeToast("中奖概率不能为空");
                return false;
            }
            if(StringUtils.isNotEmpty(list.get(i).getEndNum())){
                rate.add(list.get(i).getEndNum());
            }else {
                makeToast("中奖概率不能为空");
                return false;
            }

            if(!StringUtils.isNotEmpty(list.get(i).getPrizeTitle())){
                makeToast("请填写奖品名称");
                return false;
            }

            if(!StringUtils.isNotEmpty(list.get(i).getNum())){
                makeToast("请填写奖品数量");
                return false;
            }

            if(!StringUtils.isNotEmpty(list.get(i).getPrizeImg())){
                makeToast("请选择奖品图片");
                return false;
            }

        }
        return true;
    }




    private CustomDatePicker datePicker;
    private void initPicker(){
        /**
         * 设置年月日
         */
        datePicker = new CustomDatePicker(this, "请选择日期", new CustomDatePicker.ResultHandler() {

            @Override
            public String selectTime(String time) throws Exception {
                timeJudge(time);
                return null;
            }
        },StockUtils.getCurrentTime(),StockUtils.getYearAdd());
        datePicker.showSpecificTime(true);
        datePicker.setIsLoop(true);
    }


    private void timeJudge(String time) throws Exception {
        Date now = new Date();
        Date date = StockUtils.converToDate(time);
        if(!now.before(date)){
            makeToast("活动时间不能早于当前时间");
            return;
        }
        if(isStartTime){
            if(EndDate != null){
                if(!EndDate.before(date)){
                    tvStartTime.setText(time);
                    StartDate = date;
                }else {
                    makeToast("开始时间不能晚于结束时间");
                    return;
                }
            }else {
                tvStartTime.setText(time);
                StartDate = date;
            }

        }else {
            if(StartDate != null){
                if(!date.before(StartDate) && !date.equals(StartDate)) {
                    tvEndTime.setText(time);
                    EndDate = date;
                }else {
                    makeToast("结束时间不能早于开始时间");
                }
            }else {
                makeToast("请先选择开始时间开始时间");
            }
        }

    }




    private void timeContrast(Date startTime,Date endTime){



    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_build_event;
    }

    @Override
    protected void initView(@Nullable Bundle bundle) {
        setTitle("自建活动");
        initializeRecyclerView();
        mBuildEventPresenter = new BuildEventPresenter();
        mBuildEventPresenter.addTaskListener(this);
        mBuildEventPresenter.onStart();
        initPicker();
    }


    private String imgPath = "";



    @Override
    public void takeSuccess(TResult result) {
        if (result != null) {
            TImage image = result.getImage();
            String userShopId = UserManager.getInstance().getUserShopId();
            //上传单张图片
            if(isClickThemeLogo){
                etImgPath = image.getCompressPath();
                File file = new File(etImgPath);
                mBuildEventPresenter.uploadOssImg(userShopId,"shop",etImgPath);
                Glide.with(this)
                        .load(Uri.fromFile(file))
                        .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                        .placeholder(R.mipmap.ic_wait_logo)
                        .error(R.mipmap.ic_error)
                        .into(ivAddPicLogo);
                ivDelPicLogo.setVisibility(View.VISIBLE);
            }else {
                imgPath = image.getCompressPath();
                mBuildEventPresenter.uploadOssImg(userShopId,"shop",imgPath);
                adapter.getData().get(mPosition).setPrizeImg(imgPath);
                adapter.notifyDataSetChanged();

            }

        }
    }


    @Override
    public void setUpload(OssImageData ossImageData) {
        if(isClickThemeLogo){
            etImgPath = ossImageData.getFilePath();
        }else {
            List<ShopEventPrizeList> images = adapter.getData();
            if(adapter == null || images == null ||images.size() < 1) {
                return;
            }
            for (ShopEventPrizeList image : images) {
                if(image.getPrizeImg().equals(imgPath)){
                    image.setPrizeImgPath(ossImageData.getFilePath());
                }
            }
        }



    }

    @Override
    public void setDelImage() {
        ivAddPicLogo.setImageResource(R.mipmap.ic_add_image);
        ivDelPicLogo.setVisibility(View.GONE);
        etImgPath = "";
    }


    private int mPosition;

    private int max = 50;
    private MineEventSetAdapter adapter;
    private void initializeRecyclerView(){
        adapter = new MineEventSetAdapter(this);
        adapter.add(new ShopEventPrizeList());
        adapter.setMaxCount(max);
        adapter.setOnItemClickListener(new MineEventSetAdapter.OnItemClickListener<ShopEventPrizeList>() {
            @Override
            public void onItemClick(ShopEventPrizeList list, int position, View view) {

            }

            @Override
            public void onAddImageClick(int positon) {
                mPosition = positon;
                takePhoto();
                isClickThemeLogo = false;
            }

        });


        rv.setLongPressDragEnabled(true);
        rv.setSwipeMenuCreator(swipeMenuCreator);
        rv.setSwipeMenuItemClickListener(mMenuItemClickListener);
        rv.setSwipeItemClickListener(this);
        rv.setOnItemMoveListener(getItemMoveListener());// 监听拖拽和侧滑删除，更新UI和数据源。
        rv.setOnItemStateChangedListener(mOnItemStateChangedListener);

        //setSideslipMenu();
        rv.setLayoutManager(new LinearLayoutManager(BuildEventActivity.this));
        rv.setAdapter(adapter);
    }


    private void setAdapterItem(){
        adapter.getData().add(new ShopEventPrizeList());
        adapter.notifyDataSetChanged();
    }




    // 3. 创建侧滑菜单
    private SwipeMenuCreator swipeMenuCreator = new SwipeMenuCreator() {

        // int width = getResources().getDimensionPixelSize(R.dimen.width_80);

        // 1. MATCH_PARENT 自适应高度，保持和Item一样高;
        // 2. 指定具体的高，比如80;
        // 3. WRAP_CONTENT，自身高度，不推荐;
        int height = ViewGroup.LayoutParams.MATCH_PARENT;

        @Override
        public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {
            SwipeMenuItem deleteItem = new SwipeMenuItem(BuildEventActivity.this)
                    .setImage(R.mipmap.ic_delete_item)
                    .setBackgroundColor(getResources().getColor(R.color.white)) // 背景颜色
                    .setWidth(300) // 宽
                    .setHeight(height); //高（MATCH_PARENT意为Item多高侧滑菜单多高 （推荐使用））
            swipeRightMenu.addMenuItem(deleteItem);// 添加一个按钮到右侧侧菜单。
        }
    };

    // 4. 创建侧滑菜单的点击事件
    private SwipeMenuItemClickListener mMenuItemClickListener = new SwipeMenuItemClickListener() {
        @Override
        public void onItemClick(SwipeMenuBridge menuBridge) {
            // 任何操作必须先关闭菜单，否则可能出现Item菜单打开状态错乱。
            menuBridge.closeMenu();
            //在menuBridge中我们可以得到侧滑的这一项item的position (menuBridge.getAdapterPosition())

            int direction = menuBridge.getDirection(); // 左侧还是右侧菜单。
            int adapterPosition = menuBridge.getAdapterPosition(); // RecyclerView的Item的position。
            int menuPosition = menuBridge.getPosition(); // 菜单在RecyclerView的Item中的Position。

            //右侧侧滑事件
            if (direction == SwipeMenuRecyclerView.RIGHT_DIRECTION) {
                adapter.getData().remove(adapterPosition);
                adapter.notifyDataSetChanged();
            } else if (direction == SwipeMenuRecyclerView.LEFT_DIRECTION) {

            }
        }
    };



    /**
     * Item的拖拽/侧滑删除时，手指状态发生变化监听。
     */
    private OnItemStateChangedListener mOnItemStateChangedListener = new OnItemStateChangedListener() {
        @Override
        public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
            if (actionState == OnItemStateChangedListener.ACTION_STATE_DRAG) {
                // 拖拽的时候背景就透明了，这里我们可以添加一个特殊背景。
                viewHolder.itemView.setBackgroundColor(ContextCompat.getColor(BuildEventActivity.this, R.color.white));
            } else if (actionState == OnItemStateChangedListener.ACTION_STATE_SWIPE) {

            } else if (actionState == OnItemStateChangedListener.ACTION_STATE_IDLE) {

                // 在手松开的时候还原背景。
                ViewCompat.setBackground(viewHolder.itemView, ContextCompat.getDrawable(BuildEventActivity.this, R.color.white));
            }
        }
    };



    protected OnItemMoveListener getItemMoveListener() {
        // 监听拖拽和侧滑删除，更新UI和数据源。
        return new OnItemMoveListener() {
            @Override
            public boolean onItemMove(RecyclerView.ViewHolder srcHolder, RecyclerView.ViewHolder targetHolder) {
                // 不同的ViewType不能拖拽换位置。
                if (srcHolder.getItemViewType() != targetHolder.getItemViewType()) return false;




//                 真实的Position：通过ViewHolder拿到的position都需要减掉HeadView的数量。
                int fromPosition = srcHolder.getAdapterPosition() - rv.getHeaderItemCount();
                int toPosition = targetHolder.getAdapterPosition() - rv.getHeaderItemCount();



                Collections.swap(adapter.getData(), fromPosition, toPosition);
                adapter.notifyItemMoved(fromPosition, toPosition);



                return true;// 返回true表示处理了并可以换位置，返回false表示你没有处理并不能换位置。
            }

            @Override
            public void onItemDismiss(RecyclerView.ViewHolder srcHolder) {


            }
        };
    }


    @Override
    public void onItemClick(View itemView, int position) {
        int count = adapter.getItemCount();
        if (adapter.getListCount() == max) {
            if (position == max - 1) {
                return;
            }
        } else {
            if (position == count - 1) {
                boolean b = addAdapterHint();
                if(b){
                    setAdapterItem();
                }
                return;
            }
        }
    }


    @Override
    public void setUploadMore(List<OssImageData> ossImageData) {

    }

}
